<?php
/** 
 * @brief Session会话类 
 * @note 参考自LotusPHP的Session类
 */
class Session {
    /** 
     * Session Handler
     * 
     * @var object 
     */
    public static $sessHandler;

    /**
     * 初始化并开启Session
     * 
     * @return void
     */
    public static function init() {
        $config = Yaf_Registry::get('Config');
        $handler = $config->session->handler;
        $lifetime = $config->session->lifetime;
        if (!is_object(self::$sessHandler)) {
            $handlerName = 'Session_Handler_' . ucfirst(strtolower($handler));
            self::$sessHandler = call_user_func(array($handlerName, 'init'), $lifetime);
        }
        session_set_save_handler(
            array(&self::$sessHandler, 'open'), 
            array(&self::$sessHandler, 'close'), 
            array(&self::$sessHandler, 'read'), 
            array(&self::$sessHandler, 'write'), 
            array(&self::$sessHandler, 'destroy'), 
            array(&self::$sessHandler, 'gc')
        );
        session_start();
    }

    /**
     * 随机生成SessionID
     * 
     * @return string
     */
    public static function generateSessId() {
        return md5(time() . substr(uniqid(rand()), -6));
    }

    /**
     * 设置当前会话的SessionID
     * 
     * @param string $sessId SessionID
     * 
     * @return void
     */
    public static function setSessId($sessId) {
        session_id($sessId);
    }

    /**
     * 取得当前会话的SessionID
     * 
     * @return string
     */
    public static function getSessId() {
        return Http_Server::$cookie[session_name()];
    }
    
    /**
     * 设置$_SESSION数组中指定索引的值
     * 
     * @param string $name 索引 
     * @param mixed $value 值
     * 
     * @return void
     */
    public static function set($name, $value) {
        self::$sessHandler->write($name, $value);
    }

    /**
     * 取出$_SESSION数组中指定索引的值
     * 
     * @param string $name 索引
     * 
     * @return mixed
     */
    public static function get($name) {
        return self::$sessHandler->read($name);
    }

    /**
     * 删除指定Session ID的SESSION数据
     * 
     * @param string $sessId 指定的Session ID
     * 
     * @return void
     */
    public static function remove($sessId) {
        self::$sessHandler->destroy($sessId);
    }
    
    /**
     * 注销当前会话并删除所有Session数据
     * 
     * @return void
     */
    public static function destroy() {
        self::$sessHandler->destroy(self::getSessId());
        session_unset();
        session_destroy();
    }
}
